package com.wuyanzu.shixicoderedo.service.impl;

import com.wuyanzu.shixicoderedo.common.dto.MessageQueryDTO;
import com.wuyanzu.shixicoderedo.common.vo.MessageVO;
import com.wuyanzu.shixicoderedo.mapper.MessageMapper;
import com.wuyanzu.shixicoderedo.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
/**
 用于实现简历第一条
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper mapper;

    // 深分页阈值（若 offset 大于此值，使用 findAnchor + queryByAnchor）
    @Value("${app.paging.deep-offset-threshold}")
    private int deepOffsetThreshold;

    @Override
    public Map<String, Object> queryMessages(MessageQueryDTO dto) {
        Map<String,Object> ret = new HashMap<>();
        int offset = dto.getOffset();
        int pageSize = dto.getPageSize();

        // 优先使用 keyset（如果前端提供 lastCreatedAt & lastId）
        if (dto.getLastCreatedAt() != null && dto.getLastId() != null) {
            List<MessageVO> list = mapper.queryByKeyset(dto);
            ret.put("list", list);
            if (dto.isNeedTotal()) ret.put("total", mapper.countTotal(dto));
            return ret;
        }

        // 否则根据 offset 决定：浅分页直接 offset，深分页使用 anchor 定位
        if (offset <= deepOffsetThreshold) {
            List<MessageVO> list = mapper.queryByOffset(dto);
            ret.put("list", list);
            if (dto.isNeedTotal()) ret.put("total", mapper.countTotal(dto));
            return ret;
        }

        // 深分页：使用 findAnchor（只扫描索引叶），然后 queryByAnchor（回表 limit 次）
        Map<String,Object> anchor = mapper.findAnchor(dto, offset);
        if (anchor == null || anchor.get("anchorId") == null) {
            ret.put("list", Collections.emptyList());
            if (dto.isNeedTotal()) ret.put("total", mapper.countTotal(dto));
            return ret;
        }

        // 获取 anchorCreatedAt 为 LocalDateTime 类型
        LocalDateTime localDateTime = (LocalDateTime) anchor.get("anchorCreatedAt");

        // 将 LocalDateTime 转换为 Date
        Date anchorCreatedAt = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

        Long anchorId = ((Number) anchor.get("anchorId")).longValue();

        List<MessageVO> list = mapper.queryByAnchor(dto, anchorCreatedAt, anchorId, pageSize);
        ret.put("list", list);
        if (dto.isNeedTotal()) ret.put("total", mapper.countTotal(dto));
        return ret;
    }


    /**
     * 新增：获取最近未读消息（复用浅分页 queryByOffset）
     */
    @Override
    public Map<String, Object> getRecentUnread(Long userId, int limit) {
        Map<String, Object> ret = new HashMap<>();

        MessageQueryDTO dto = new MessageQueryDTO();
        dto.setUserId(userId);
        dto.setPage(1);
        dto.setPageSize(limit);
        dto.setStatus(0);      // 0 = 未读
        dto.setNeedTotal(false);

        List<MessageVO> list = mapper.queryByOffset(dto);
        ret.put("list", list);
        return ret;
    }
}
